package dyyx.jwt;

import java.security.Key;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.spec.SecretKeySpec;

import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtTest {
	
	public static void main(String[] args) throws Exception {	
		//
		
		System.out.println("hello,jwt");
		// 签名算法  
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		String secretKeyStr = "http://codefun007.xyz/";
		// 秘钥 
		byte[] secretKeyBytes = secretKeyStr.getBytes();
		Key signingKey = new SecretKeySpec(secretKeyBytes, signatureAlgorithm.getJcaName());
		Map<String,Object> claimsMap = new HashMap<String,Object>();
		claimsMap.put("name","dyyx");
		claimsMap.put("age",30);
		JwtBuilder builder = Jwts.builder()
		        // .setSubject("subject")
		        // .setIssuer("issuer")
		        .addClaims(claimsMap)
		        .signWith(signatureAlgorithm, signingKey);
		
	    String jwt = builder.compact();
	    // eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiZHl5eCIsImFnZSI6MzB9.M1hIZLeSej7CVwLJ4r1qRjG1fXpJYfylfUDcoUoRBKk
		System.out.println(jwt);
				
		// parse
		JwtParser parser = Jwts.parser();
		parser.setSigningKey(signingKey);
		
		Jwt jwtobj = parser.parse(jwt);
		// header={alg=HS256},body={name=dyyx, age=30},signature=M1hIZLeSej7CVwLJ4r1qRjG1fXpJYfylfUDcoUoRBKk
		System.out.println(jwtobj);
		
		
	}
}
